import React, { useEffect, useState } from 'react';
import { Image } from 'antd';
import cls from './index.module.less';
import { ISysFileInfo } from '@/ts/core';
import OpenFileDialog from '@/components/OpenFileDialog';
import { FileItemShare } from '@/ts/base/model';
import TypeIcon from '@/components/Common/GlobalComps/typeIcon';
import { command } from '@/ts/base';
import { ellipsisText } from '@/utils';
import { Button, TextArea } from 'devextreme-react';
import { ITextBoxOptions } from 'devextreme-react/text-box';
import UploadIcon from '@/components/Common/FileUpload/uploadIcon';
import OrgIcons from '@/components/Common/GlobalComps/orgIcons';

const SelectFilesItem: React.FC<ITextBoxOptions> = (props) => {
  const [open, setOpen] = useState(false);
  const [fileList, setFileList] = useState<FileItemShare[]>([]);
  const uploadLabelStyle = { paddingBottom: '10px', color: '#999', fontSize: '12px' };

  useEffect(() => {
    if (props.value && props.value.length > 0) {
      try {
        var temps = JSON.parse(props.value);
        if (temps && Array.isArray(temps) && temps.length > 0) {
          setFileList(temps);
        }
      } catch (error) {
        console.error(error);
      }
    }
  }, [props.value]);

  return (
    <TextArea {...props} height={'auto'} width={'100%'} defaultValue="" value="">
      <div className={cls.imageUploader}>
        {fileList.map((i, x) => {
          return (
            <div
              className={cls.fileItem}
              key={i.name + x}
              title={i.name}
              onClick={() => {
                command.emitter('executor', 'open', i, 'preview');
              }}>
              {i?.contentType &&
              ['image/jpeg', 'image/png', 'image/webp'].includes(i?.contentType) ? (
                <Image width={300} src={i.thumbnail} preview={false} />
              ) : (
                <React.Fragment>
                  <TypeIcon iconType={i.contentType ?? '文件'} size={50} />
                  <span>{ellipsisText(i.name, 10)}</span>
                </React.Fragment>
              )}
              {!(props.readOnly || props.disabled) && (
                <Button
                  icon="close"
                  type="danger"
                  stylingMode="text"
                  onClick={(e) => {
                    e?.event?.stopPropagation();
                    setFileList(fileList.filter((_, i) => i !== x));
                  }}
                />
              )}
            </div>
          );
        })}
        <div>
          <Button
            hint="云端上传"
            type="default"
            stylingMode="text"
            height={60}
            onClick={React.useCallback(() => {
              setOpen(true);
            }, [])}
            visible={props.readOnly != true}>
            <div>
              <OrgIcons type="/toolbar/cloudUpload" size={38} notAvatar />
              <div style={uploadLabelStyle}>云端上传</div>
            </div>
          </Button>
          <Button
            hint="本地上传"
            type="default"
            stylingMode="text"
            height={60}
            visible={props.readOnly != true}>
            <div>
              <UploadIcon
                size={38}
                onSelected={async (file) => {
                  if (file) {
                    props.onValueChanged?.({
                      value: JSON.stringify([...fileList, file.shareInfo()]),
                    } as any);
                  }
                }}
              />
              <div style={uploadLabelStyle}>本地上传</div>
            </div>
          </Button>
        </div>
      </div>
      {open && (
        <OpenFileDialog
          multiple
          rootKey={'disk'}
          accepts={['文件']}
          allowInherited
          maxCount={(props.maxLength ?? 100) as number}
          onCancel={() => setOpen(false)}
          onOk={(files) => {
            if (files.length > 0) {
              props.onValueChanged?.({
                value: JSON.stringify([
                  ...fileList,
                  ...files.map((i) => (i as ISysFileInfo).shareInfo()),
                ]),
              } as any);
            }
            setOpen(false);
          }}
        />
      )}
    </TextArea>
  );
};

export default SelectFilesItem;
